package com.webserver.controllers;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 *  处理用户相关业务
 */
public class UserController {
    /**
     *  用户注册
     */
    public void reg(HttpRequest request, HttpResponse response) {
        System.out.println("开始处理注册业务...");
        /*
            1.通过request得到注册页面上form表单中用户输入的注册信息
            2.将form表单数据以一个User对象形式保存并序列化到文件中
              文件名为:用户名.user
            3.设置response响应注册成功页面
         */
        /*
            这里getParameter的参数应当和对应页面上form表单中输入框的name属性指定的一致.
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        /*
            两个必要的验证工作
            如果上述四个信息有空的,则直接跳转页面提示用户输入信息有误.
            提示页面:reg_error.html

            如果输入的用户已经存在,则直接跳转页面提示用户该用户已存在.
            提示页面:have_user.html
         */
        if (username==null || password==null || nickname==null || ageStr==null || !ageStr.matches("[0-9]+")){
            File file = new File("./webapps/myweb/reg_error.html");
            response.setEntity(file);
            return;
        }
        File file = new File(username+".user");
        if (file.exists()){
            file = new File("./webapps/myweb/have_user.html");
            response.setEntity(file);
            return;
        }

        int age = Integer.parseInt(ageStr);

        //2
        User user = new User(username,password,nickname,age);
        try (
                FileOutputStream fos = new FileOutputStream(username+".user");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);

            //3
            file = new File("./webapps/myweb/reg_success.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("注册业务处理完成.");
    }

    public void login(HttpRequest request,HttpResponse response) {
        System.out.println("开始登录...");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+","+password);

        if (username==null || password==null){
            File file = new File("./webapps/myweb/login_oo.html");
            response.setEntity(file);
            return;
        }
        File file = new File(username+".user");
        if (file.exists()){
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis)
            ){
                User u = (User) ois.readObject();
                if (u.getPassword().equals(password)){
                    file = new File("./webapps/myweb/login_success.html");
                    response.setEntity(file);
                    return;
                }else {
                    file = new File("./webapps/myweb/login_xx.html");
                    response.setEntity(file);
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else {
            file = new File("./webapps/myweb/login_fail.html");
            response.setEntity(file);
        }
        System.out.println("登录处理完成.");
    }

    public void delete(HttpRequest request,HttpResponse response) {
        System.out.println("开始处理删除业务...");

        String username = request.getParameter("username");
        File file = new File(username+".user");
        if (file.exists()){
            file.delete();
            response.sendRedirect("./showAllUser");
        }
        System.out.println("删除业务处理完成.");
    }

    public void userList(HttpRequest request,HttpResponse response) {
        System.out.println("开始生成动态页面...");

        /*
            流程
            1.读取所有的用户信息(获取所有的.user文件并进行反序列化操作)
            2.将用户信息拼接为一个html内容(生成动态页面的所有数据内容)
            3.将生成的页面响应给客户端
         */

        List<User> userList = new ArrayList<>();//保存所有注册用户
        //先获取所有的.user文件
        File dir = new File(".");//项目目录
        if (dir.isDirectory()) {
            File[] subs = dir.listFiles(
                    //lambda创建文件过滤器,条件:名字以.user结尾的子项
                    (f) -> f.getName().endsWith(".user")
            );
            for (File userFile : subs) {
                try (
                        ObjectInputStream ois = new ObjectInputStream(
                                new FileInputStream(userFile)
                        )
                ) {
                    User user = (User) ois.readObject();
                    userList.add(user);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

             /*
                 2将所有的用户信息生成一个html页面
              */
            try {
                //设置响应头Content-Type用来告诉浏览器我们拼的是个页面
                response.setContentType("text/html");

                PrintWriter pw = response.getWriter();
                pw.println("<!DOCTYPE html>");
                pw.println("<html lang=\"en\">");
                pw.println("<head>");
                pw.println("<meta charset=\"UTF-8\">");
                pw.println("<title>用户列表</title>");
                pw.println("</head>");
                pw.println("<body>");
                pw.println("<center>");
                pw.println("<h1>用户列表</h1>");
                pw.println("<table border=\"1\">");
                pw.println("<tr><td>用户名</td><td>密码</td><td>昵称</td><td>年龄</td><td>操作</td></tr>");
                for (User user : userList) {
                    pw.println("<tr>");
                    pw.println("    <td align=\"center\">" + user.getUsername() + "</td>");
                    pw.println("    <td align=\"center\">" + user.getPassword() + "</td>");
                    pw.println("    <td align=\"center\">" + user.getNickname() + "</td>");
                    pw.println("    <td align=\"center\">" + user.getAge() + "</td>");
                    pw.println("    <td align=\"center\"><a href='./deleteUser?username="+user.getUsername()+"'>删除</a></td>");
                    pw.println("</tr>");
                }
                pw.println("</table>");
                pw.println("</center>");
                pw.println("</body>");
                pw.println("</html>");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("动态页面生成完毕.");
    }

    /**
     *  发布文章
     * @param request
     * @param response
     */
    public void create(HttpRequest request,HttpResponse response) {
        System.out.println("开始编辑...");
        String title = request.getParameter("title");
        String user = request.getParameter("user");
        String content = request.getParameter("content");
        System.out.println(title + "," + user + "," +content);
        if (title==null) {
            File file = new File("./webapps/myweb/createArticle_oo.html");
            response.setEntity(file);
            return;
        }
        File file = new File(title+".article");
        if (file.exists()) {
            file = new File("./webapps/myweb/createArticle_xx.html");
            response.setEntity(file);
            return;
        }
        User author = new User(title,user,content);
        try (
                FileOutputStream fos = new FileOutputStream(title+".article");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(author);
            file = new File("./webapps/myweb/createArticle_ok.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文章编辑完成.");
    }

    /**
     *  生成显示文章列表页面
     * @param request
     * @param response
     */
    public void articleList(HttpRequest request,HttpResponse response) {
        System.out.println("开始...");
        List<User> list = new ArrayList<>();
        File dir = new File(".");//项目目录
        if (dir.isDirectory()) {
            File[] subs = dir.listFiles(
                    //lambda创建文件过滤器,条件:名字以.user结尾的子项
                    (f) -> f.getName().endsWith(".article")
            );
            for (File file : subs) {
                try (
                        ObjectInputStream ois = new ObjectInputStream(
                                new FileInputStream(file)
                        )
                ) {
                    User user = (User) ois.readObject();
                    list.add(user);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //设置响应头Content-Type用来告诉浏览器我们拼的是个页面
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>文章列表</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>文章列表</h1>");
        pw.println("<table border=\"1\">");
        pw.println("<tr><td align=\"center\">标题</td><td align=\"center\">作者</td></tr>");
        //循环userList中的每个用户，来生成对应行
        for (User article : list) {
            pw.println("<tr>");
            pw.println("    <td align=\"center\">" + article.getTitle() + "</td>");
            pw.println("    <td align=\"center\">" + article.getUser() + "</td>");
            pw.println("</tr>");
        }
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");
        System.out.println("结束");
    }
}